<template>
  <div class="search-container">
    <!-- 搜索栏事件监听 -->
    <form class="search" action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :searchText="searchText" />
    <!-- 搜索建议 -->
    <search-suggestion v-else-if="searchText" :searchText="searchText" @search="onSearch" />
    <!-- 搜索历史 -->
    <search-history v-else :search-histories="searchHistories" @clear-search-history="searchHistories = []" @search="onSearch"/>

  </div>
</template>

<script>
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import SearchResult from './components/search-result'
import { setItem, getItem } from '@/utils/storage'
export default {
  name: 'SearchPage',
  components: {
    SearchHistory,
    SearchResult,
    SearchSuggestion
  },
  data () {
    return {
      searchText: '',
      isResultShow: false,
      searchHistories: getItem('serach-histories') || []
    }
  },
  watch: {
    searchHistories (val) {
    // 同步到本地存储
      setItem('serach-histories', val)
    }
  },
  created () {},
  methods: {
    onSearch (val) {
      this.searchText = val
      // 存储历史记录
      const index = this.searchHistories.indexOf(val)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(val)
      // 搜素组件显示出来
      this.isResultShow = true
    },
    onCancel () {
      this.$toast('取消')
      this.$router.back()
    }
  }
}
</script>

<style lang="less" scoped>
.search-container {
    padding-top: 106px;
    .search {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        z-index: 1;
    }
    .van-search__action {
        color: #ffffff;
    }
}
</style>
